import { createStore } from "vuex";
import createPersistedState from "vuex-persistedstate"
import { routes } from '@/router'

//const username = localStorage.getItem("username")

//过滤当前用户权限的路由集合
function filterRoutes(routes, roles) {
    let result = []
    routes.forEach(route => {
        const tmp = { ...route }
        if (roles.includes(tmp.name)) {
            if (tmp.children) {
                tmp.children = filterRoutes(tmp.children, roles)
            }
            result.push(tmp)
        }
    })
    return result

}

const store = createStore({
    state: {
        //登录用户名
        username: "",
        //权限数据
        pageRoles: [],
        //用户角色
        role: "",


        //左侧菜单是否收起
        isFold: false,
    },
    getters: {
        permissionRoutes(state) {
            const arr = routes.filter((item) => !item.hidden);
            if (state.role === 2) {
                return arr
            }
            return filterRoutes(arr, state.pageRoles);
        },
    },
    mutations: {
        setUsername(state, username) {
            state.username = username;


            //localStorage.setItem("username", username);
        },

        setState(state, payload) {
            state.username = payload.adminname;
            state.pageRoles = payload.checkedkeys;
            state.role = payload.role;
        },


        toggleIsFold(state) {
            state.isFold = !state.isFold;
        },
    },
    plugins: [createPersistedState({
        //额外配置

        //指定本地存储使用上面：默认是window.localStorage
        // storage: window.sessionStorage,


        //指定state存储的数据
        // reducer: (state) => {
        //     return {
        //         username: state.username,
        //     };
        //}
    })],
});

export default store;